package cn.yiya.shiji.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nineoldandroids.view.ViewHelper;

import java.util.ArrayList;
import java.util.List;

import cn.yiya.shiji.R;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.entity.BackgroundItem;
import cn.yiya.shiji.entity.MallLimitOptionInfo;
import cn.yiya.shiji.fragment.BrandsGoodsShowFragment;
import cn.yiya.shiji.fragment.BrandsNewestFragment;
import cn.yiya.shiji.fragment.BrandsWorkDetailFragment;
import cn.yiya.shiji.netroid.Netroid;
import cn.yiya.shiji.utils.SimpleUtils;
import cn.yiya.shiji.utils.Util;
import cn.yiya.shiji.views.DisableViewPage;
import cn.yiya.shiji.views.FloatingActionButton;
import cn.yiya.shiji.views.KenBurnsSupportView;

/**
 * Created by chenjian on 2015/11/10.
 */
public class SingleBrandOrderActivity extends AppCompatActivity implements AppBarLayout.OnOffsetChangedListener {

    private static final float PERCENTAGE_TO_SHOW_TITLE_AT_TOOLBAR = 0.9f;
    private static final int ALPHA_ANIMATIONS_DURATION = 200;

    private boolean mIsTheTitleVisible = false;
    private boolean mIsTheTitleContainerVisible = true;

    private KenBurnsSupportView ivBackground;
    private ImageView ivLogo;
    private FloatingActionButton btnFollow;
    private TextView tvDesc;
    private DisableViewPage mViewPager;
    private TextView tvTitle;
    CollapsingToolbarLayout collapsingToolbar;

    private AppBarLayout appBarLayout;
    private Toolbar mToolbar;
    public String tagWork = "";
    private boolean bFirst = true;
    private boolean followed;
    private int tag_id;
    public int brand_id;
    public boolean bMoreIn = false;

    private boolean bCollapse = true;
    private OnMiddleCosllapsingClick onMiddleCosllapsingClick;
    private TabLayout tabLayout;
    private DrawerLayout mDrawerLayout;
    private BackgroundItem item;
    private ImageView ivBack;

    public static final int REQUEST_LOGIN = 100;

    private String[] mTitle = new String[]{"最新", "商品", "晒单"};

    public boolean needOrder;
    public int orderId;
    private int type;               // 商品详情晒单列表跳转过来为2  则显示成晒单界面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_order);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            brand_id = intent.getIntExtra("brand_id", 0);
            type = intent.getIntExtra("type", 0);
        }

        //右侧侧滑筛选菜单
        mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerlayout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);

        ivBackground = (KenBurnsSupportView) this.findViewById(R.id.backdrop);
        tvDesc = (TextView) this.findViewById(R.id.song);
        mViewPager = (DisableViewPage) this.findViewById(R.id.viewpager);
        ivBack = (ImageView) findViewById(R.id.toolbar_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        tvTitle = (TextView) this.findViewById(R.id.collpase_title);
        ivLogo = (ImageView) this.findViewById(R.id.brands_logo);
        btnFollow= (FloatingActionButton) this.findViewById(R.id.btn_follow);
        btnFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnFollow.setLineMorphingState((btnFollow.getLineMorphingState() + 1) % 2, true);
                if (item.is_follow()) {
                    new RetrofitRequest<>(ApiRequest.getApiShiji().postFollowBrands(String.valueOf(tag_id))).handRequest(
                            new MsgCallBack() {
                                @Override
                                public void onResult(HttpMessage msg) {
                                    if (msg.isSuccess()) {
                                        Util.toast(SingleBrandOrderActivity.this, "已取消订阅", true);
                                        item.setIs_follow(false);
                                    } else if(msg.isLossLogin()){
                                        btnFollow.setLineMorphingState((btnFollow.getLineMorphingState() + 1) % 2, true);
                                        Intent intent = new Intent(SingleBrandOrderActivity.this, LoginActivity.class);
                                        startActivityForResult(intent, REQUEST_LOGIN);
                                        SingleBrandOrderActivity.this.overridePendingTransition(R.anim.slide_in_top_buttom, R.anim.slide_out_top_buttom);
                                    } else {
                                        Util.toast(SingleBrandOrderActivity.this, "取消失败", true);
                                        btnFollow.setLineMorphingState((btnFollow.getLineMorphingState() + 1) % 2, true);
                                    }
                                }
                            }
                    );
                } else {
                    new RetrofitRequest<>(ApiRequest.getApiShiji().postFollowBrands(String.valueOf(tag_id))).handRequest(
                            new MsgCallBack() {
                                @Override
                                public void onResult(HttpMessage msg) {
                                    if (msg.isSuccess()) {
                                        Util.toast(SingleBrandOrderActivity.this, "已订阅", true);
                                        item.setIs_follow(true);
                                    } else if(msg.isLossLogin()){
                                        btnFollow.setLineMorphingState((btnFollow.getLineMorphingState() + 1) % 2, true);
                                        Intent intent = new Intent(SingleBrandOrderActivity.this, LoginActivity.class);
                                        startActivityForResult(intent, REQUEST_LOGIN);
                                        SingleBrandOrderActivity.this.overridePendingTransition(R.anim.slide_in_top_buttom, R.anim.slide_out_top_buttom);
                                    }else {
                                        Util.toast(SingleBrandOrderActivity.this, "订阅失败", true);
                                        btnFollow.setLineMorphingState((btnFollow.getLineMorphingState() + 1) % 2, true);
                                    }
                                }
                            }
                    );
                }
            }
        });


        if (mViewPager != null) {
            setupViewPager(mViewPager);
        }

        initDrawerEvent();

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        for (int i = 0; i < tabLayout.getTabCount(); i++){
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            View view = LayoutInflater.from(this).inflate(R.layout.single_brand_tab_item, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.width = SimpleUtils.getScreenWidth(this)/3;
            view.setLayoutParams(layoutParams);
            TextView tvTab = (TextView)view.findViewById(R.id.tv_tab);
            tvTab.setText(mTitle[i]);
            if(i == 2){
                view.findViewById(R.id.view_right).setVisibility(View.INVISIBLE);
            }
            tab.setCustomView(view);
        }

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
//                Log.e("tag", "select:" + tab.getPosition());
//                if (tab.getPosition() == 1) {
//                    tab.setText("所有人群 ∨");
//                    if (onMiddleCosllapsingClick != null) {
//                        bCollapse = true;
//                        bFirst = true;
//                        onMiddleCosllapsingClick.onCollapseClick(bCollapse);
//                    }
//                } else {
//                    tabLayout.getTabAt(1).setText("商品");
//                }
                mViewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
//                if (tab.getPosition() == 1) {
//                    if (bFirst) {
//                        bFirst = false;
//                        return;
//                    } else {
//                        if (bCollapse) {
//                            tab.setText("所有人群 ∧");
//                        } else {
//                            tab.setText("所有人群 ∨");
//                        }
//                        if (onMiddleCosllapsingClick != null) {
//                            onMiddleCosllapsingClick.onCollapseClick(!bCollapse);
//                            bCollapse = !bCollapse;
//                        }
//                    }
//                }
            }
        });

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        mToolbar.setTitle("");

        startAlphaAnimation(tvTitle, 0, View.INVISIBLE);

        CoordinatorLayout coordinator = (CoordinatorLayout) findViewById(R.id.main_content);

        appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
        appBarLayout.addOnOffsetChangedListener(this);
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        if (behavior != null) {
            behavior.setTopAndBottomOffset(100);
            behavior.onNestedPreScroll(coordinator, appBarLayout, null, 0, 1, new int[2]);
        }

        collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.brand_detail_backimage);

        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {

                Palette.Swatch vibrant = palette.getVibrantSwatch();//有活力
                int defaultColor = getResources().getColor(R.color.blue);
                int defaultTitleColor = getResources().getColor(R.color.white);
                int bgColor = palette.getDarkVibrantColor(defaultColor);
                int titleColor = palette.getLightVibrantColor(defaultTitleColor);

                int color1 = vibrant.getBodyTextColor();//内容颜色
                int color2 = vibrant.getTitleTextColor();//标题颜色
                int color3 = vibrant.getRgb();//rgb颜色
                collapsingToolbar.setContentScrimColor(color1);
//                collapsingToolbar.setCollapsedTitleTextColor(getResources().getColor(R.color.white));
//                collapsingToolbar.setExpandedTitleColor(titleColor);
            }
        });


        getDetaiData();
    }

    private void initDrawerEvent() {
        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerStateChanged(int newState) {
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                View mContent = mDrawerLayout.getChildAt(0);
                View mMenu = drawerView;
                float scale = 1 - slideOffset;
                float rightScale = 0.8f + scale * 0.2f;

                ViewHelper.setTranslationX(mContent,
                        -mMenu.getMeasuredWidth() * slideOffset);
                ViewHelper.setPivotX(mContent, mContent.getMeasuredWidth());
                ViewHelper.setPivotY(mContent,
                        mContent.getMeasuredHeight() / 2);
                mContent.invalidate();
                ViewHelper.setScaleX(mContent, rightScale);
                ViewHelper.setScaleY(mContent, rightScale);

            }

            @Override
            public void onDrawerOpened(View drawerView) {
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                mDrawerLayout.setDrawerLockMode(
                        DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
            }
        });
    }

    private void getDetaiData() {
        new RetrofitRequest<BackgroundItem>(ApiRequest.getApiShiji().getBrandsHeaderDetail(String.valueOf(brand_id)))
                .handRequest(new MsgCallBack() {
                    @Override
                    public void onResult(HttpMessage msg) {
                        if (msg.isSuccess()) {
                            item = (BackgroundItem) msg.obj;
                            if (item != null) {
                                followed = item.is_follow();
                                tag_id = item.getTag_id();
                                if(tag_id!=0) {
                                    btnFollow.setVisibility(View.VISIBLE);
                                    if (followed) {
                                        btnFollow.setLineMorphingState(1, false);
                                    } else {
                                        btnFollow.setLineMorphingState(0, false);
                                    }
                                }else {
                                    btnFollow.setVisibility(View.GONE);
                                }
                                if (!TextUtils.isEmpty(item.getImage())) {
                                    Netroid.displayImage(item.getImage(), ivBackground);
                                }
                                ivBackground.setStart();
                                tvDesc.setText(item.getDes());
                                tvDesc.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent();
                                        intent.putExtra("des", item.getDes());
                                        intent.putExtra("logo", item.getLogo());
                                        intent.putExtra("name", item.getName());
                                        intent.setClass(SingleBrandOrderActivity.this, DesDetailsActivity.class);
                                        startActivity(intent);
                                    }
                                });
                                tvTitle.setText(item.getName());
                                if (!TextUtils.isEmpty(item.getLogo()))
                                    Netroid.displayImage(Util.transfer(item.getLogo()), ivLogo);

                                if (!TextUtils.isEmpty(item.getTag())) {
                                    tagWork = item.getTag();

                                } else
                                    tagWork = item.getName();

                                //tagWork = tagWork.replace(" ", "%20");
                                if (getIntent() != null  && getIntent().getBooleanExtra("frag_work", false)) {
                                    mViewPager.setCurrentItem(2);
                                }
                            }
                        }
                        mViewPager.setCurrentItem(type);
                    }
                });
    }




    @Override
    public boolean dispatchTouchEvent(MotionEvent motionEvent) {
        try {
            return super.dispatchTouchEvent(motionEvent);
        } catch (NullPointerException e) {
            return false;
        }
    }

    private void setupViewPager(DisableViewPage viewPager) {
        BrandsAdapter adapter = new BrandsAdapter(getSupportFragmentManager());
        adapter.addFragment(new BrandsNewestFragment(), "最新");
        adapter.addFragment(new BrandsGoodsShowFragment(), "商品");
        adapter.addFragment(new BrandsWorkDetailFragment(), "晒单");
        viewPager.setPagingEnabled(false);
        viewPager.setAdapter(adapter);
    }

    public static void startAlphaAnimation(View v, long duration, int visibility) {
        AlphaAnimation alphaAnimation = (visibility == View.VISIBLE)
                ? new AlphaAnimation(0f, 1f)
                : new AlphaAnimation(1f, 0f);

        alphaAnimation.setDuration(duration);
        alphaAnimation.setFillAfter(true);
        v.startAnimation(alphaAnimation);
    }

    static class BrandsAdapter extends FragmentStatePagerAdapter {

        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

        public BrandsAdapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return null;
        }
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
        int maxScroll = appBarLayout.getTotalScrollRange();
        float percentage = (float) Math.abs(i) / (float) maxScroll;
        tvDesc.setAlpha((1 - percentage));
        ivLogo.setAlpha((1 - percentage));

        handleToolbarTitleVisibility(percentage);
    }

    private void handleToolbarTitleVisibility(float percentage) {
        if (percentage >= PERCENTAGE_TO_SHOW_TITLE_AT_TOOLBAR) {

            if (!mIsTheTitleVisible) {
                startAlphaAnimation(tvTitle, ALPHA_ANIMATIONS_DURATION, View.VISIBLE);
                mIsTheTitleVisible = true;
            }

        } else {

            if (mIsTheTitleVisible) {
                startAlphaAnimation(tvTitle, ALPHA_ANIMATIONS_DURATION, View.INVISIBLE);
                mIsTheTitleVisible = false;
            }
        }
    }

    public interface OnMiddleCosllapsingClick {
        public void onCollapseClick(boolean bCollapse);

        public void onFilterClick(MallLimitOptionInfo mInfos);

        public void onMoreClick(int id);
    }


    public void setOnMiddleCosllapsingClick(OnMiddleCosllapsingClick onMiddleCosllapsingClick) {
        this.onMiddleCosllapsingClick = onMiddleCosllapsingClick;
    }

    public void setTitleText(String title) {
        tabLayout.getTabAt(1).setText(title);
    }

//    public void OpenRightMenu(MallLimitOptionInfo mInfos) {
//        Fragment fragment = new RightFilterFragment();
//        Bundle bundle = new Bundle();
//        if (mInfos != null) {
//            bundle.putString("data", new Gson().toJson(mInfos));
//        }
//        bundle.putInt("type", 1);
//        fragment.setArguments(bundle);
//        FragmentManager fragmentManager = getSupportFragmentManager();
//        fragmentManager.beginTransaction().replace(R.id.filter_content, fragment).commit();
//        mDrawerLayout.openDrawer(Gravity.RIGHT);
//        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED,
//                Gravity.RIGHT);
//    }

    public void getCommitData(MallLimitOptionInfo mInfo) {
        mDrawerLayout.closeDrawers();
        if (onMiddleCosllapsingClick != null) {
            onMiddleCosllapsingClick.onFilterClick(mInfo);
        }
    }

    public void setCurTabToGoods(int id) {
        needOrder = true;
        orderId = id;
        mViewPager.setCurrentItem(1);

//        if (onMiddleCosllapsingClick != null) {
//            onMiddleCosllapsingClick.onMoreClick(id);
//        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_LOGIN) {
                getDetaiData();
            }
        }
    }
}
